package com.open.capacity.notice.processor.impl;

import java.net.URLEncoder;

import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.open.capacity.notice.dmo.SendMessageTask;
import com.open.capacity.notice.enums.MsgType;
import com.open.capacity.notice.processor.AbstractCreateTaskProcessor;
import com.open.capacity.notice.processor.CreateTaskProcessor;
import com.open.capacity.notice.provider.NoticeTemplateFacotoy;
import com.open.capacity.notice.provider.core.NoticeProvider;
import com.open.capacity.notice.provider.sms.SmsProperties;
import com.open.capacity.notice.provider.sms.interactive.req.SendSmsRequest;
import com.open.capacity.notice.service.SendMessageJobService;
import com.open.capacity.notice.service.SendMessageLogService;
import com.open.capacity.notice.service.SendMessageTaskService;

import lombok.SneakyThrows;

/**
 * 短信文本类型
 */
@Service
public class CreateSmsTextTaskProcessor extends AbstractCreateTaskProcessor implements CreateTaskProcessor {

	private final String CHARTSET = "utf-8";

	public CreateSmsTextTaskProcessor(ObjectMapper objectMapper, SendMessageTaskService sendMessageTaskService,
			SendMessageJobService sendMessageJobService, SendMessageLogService sendMessageLogService,
			TransactionTemplate transactionTemplate, NoticeTemplateFacotoy noticeTemplateFacotoy) {
		super(objectMapper, sendMessageTaskService, sendMessageJobService, sendMessageLogService, transactionTemplate,
				noticeTemplateFacotoy);
	}

	/**
	 * 构建发送短信消息
	 */
	@Override
	@SneakyThrows
	public void sendMessage(SendMessageTask task) {
		Long ts = System.currentTimeMillis();
		SmsProperties smsProperties = noticeTemplateFacotoy.getNoticeTemplate(task.getSendType())
				.<SmsProperties>getProperties();
		String sign = MD5Encoder.encode((smsProperties.getUserId() + ts + smsProperties.getApikey()).getBytes());
		SendSmsRequest request = SendSmsRequest.builder().userid(smsProperties.getUserId()).mobile(task.getRececiver())
				.msgcontent(URLEncoder.encode(task.getSendMessage(), CHARTSET)).sign(sign)
				// .time(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")))
				.messageid(task.getId()).ts(ts).build();
		super.sendMessage(request, task);
	}

	@Override
	public boolean supports(SendMessageTask sendMessageTask) {
		return NoticeProvider.SMS.getCode().equals(sendMessageTask.getSendType())
				&& MsgType.TEXT == sendMessageTask.getMsgType();
	}

}
